/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hcsc.datapower.CMDB.daoImpl;

import com.hcsc.datapower.CMDB.dao.AbstractDao;
import com.hcsc.datapower.CMDB.dao.UserDao;
import com.hcsc.datapower.CMDB.integration.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
/**
 *
 * @author I307211
 */
public class UserDaoImpl extends AbstractDao implements UserDao {
    private static final String TABLE = "Users";
    
    @Override
    public int createUser(User user) {
        String sql = "INSERT INTO " + TABLE +" Values ( ?, ? , ?, ? , ? ,?, ?) ";
        return jdbcTemplate.update(sql, new Object[] {  
            user.getUserName(), 
            user.getPassword(),
            user.getAuthLevel(),
            user.getFirstName(),
            user.getLastName(),
            user.getWhoUpdated(),
            user.getTimeUpdate()
        } );
    }

    @Override
    public User getUser(String username) {
        String sql = "SELECT * FROM " + TABLE +  " where Username = ?";
        return (User) jdbcTemplate.queryForObject(sql, new UserMapper(), new Object[] {String.valueOf(username)});
    }

    @Override
    public int deleteUser(String username) {
        String sql = "DELETE FROM Users WHERE Username= ? ";
        return jdbcTemplate.update(sql, new Object[] { username } );
    }

    @Override
    public int updateUser(User user) {
        String sql = "UPDATE " + TABLE + " SET " +
                "Password= ?" +
                "AuthLevel= ? " +
                "FirstName= ? " +
                "LastName=?" +
                "WhoUpdated=?" +
                "TimeUpdate=?";
        return jdbcTemplate.update(sql, new Object[] {  
            user.getPassword(),
            user.getAuthLevel(),
            user.getFirstName(),
            user.getLastName(),
            user.getWhoUpdated(),
            user.getTimeUpdate()
        } );
    }

    @Override
    public List<User> getAllUsers() {
        String sql = "SELECT * FROM " + TABLE ;
        List<User> tmp = this.jdbcTemplate.query(sql, new UserMapper());
        
        if(tmp!=null)
            return tmp;
        return null;
    }
    
    private static final class UserMapper implements RowMapper {

        public Object mapRow(ResultSet rs, int i) throws SQLException {
            User usr = new User();
                usr.setUserName(rs.getString("Username"));
                usr.setPassword(rs.getString("Password"));
                usr.setAuthLevel(rs.getString("AuthLevel"));
                usr.setFirstName(rs.getString("FirstName"));
                usr.setLastName(rs.getString("LastName"));
                usr.setWhoUpdated(rs.getString("WhoUpdated"));
                return usr;
        }
    }
    
}
